package com.example.demo.mapper;


import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.dto.CommentWithGoodsDTO;
import com.example.demo.dto.CommentWithUserDTO;
import com.example.demo.entity.Comments;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * <p>
 * 评论模块 Mapper 接口
 * </p>
 */
@Mapper
public interface CommentsMapper extends BaseMapper<Comments> {
//    @Select("SELECT * FROM comments WHERE c_goods_id = #{goodsId}")
//    List<Comments> selectByGoods(@Param("goodsId") Integer goodsId);

    @Select("SELECT * FROM comments WHERE c_user_id = #{userId}")
    List<Comments> selectByUser(@Param("userId") Integer userId);

    @Select("<script>" +
            "SELECT * FROM comments " +
            "<where>" +
            "   <if test='keyword != null'>" +
            "       c_bio LIKE CONCAT('%', #{keyword}, '%') " +
            "   </if>" +
            "</where>" +
            "</script>")
    IPage<Comments> selectCommentsPage(Page<Comments> page, @Param("keyword") String keyword);

    // 使用 DTO 返回包含用户名的评论数据
    @Select("SELECT c.*, u.u_name AS userName " +
            "FROM comments c " +
            "LEFT JOIN user u ON c.c_user_id = u.u_id " +
            "WHERE c.c_goods_id = #{goodsId}")
    List<CommentWithUserDTO> selectByGoodsIdWithUser(@Param("goodsId") Integer goodsId);

    @Select("<script>" +
            "SELECT " +
            "   c.c_id AS cId, " +
            "   c.c_user_id AS cUserId, " +
            "   c.c_goods_id AS cGoodsId, " +
            "   c.c_bio AS cBio, " +
            "   u.u_name AS userName, " +
            "   g.g_name AS productName, " +
            "   g.g_price AS productPrice, " +
            "   g.g_category AS category, " +
            "   g.g_description AS description " +
            "FROM comments c " +
            "LEFT JOIN user u ON c.c_user_id = u.u_id " +
            "LEFT JOIN goods g ON c.c_goods_id = g.g_id " +
            "WHERE c.c_user_id = #{userId} " +
            "<if test='keyword != null'>" +
            "   AND c.c_bio LIKE CONCAT('%', #{keyword}, '%') " +
            "</if>" +
            "ORDER BY c.c_id DESC" +
            "</script>")
    IPage<CommentWithGoodsDTO> selectCommentsWithGoodsByUser(Page<CommentWithGoodsDTO> page,
                                                             @Param("userId") Integer userId,
                                                             @Param("keyword") String keyword);
}
